package services

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"gin_template/core/setting"
	"gin_template/core/snowflake"
	timeUnit "gin_template/data/time"
	"gin_template/models"
	"sort"
	"strconv"
	"strings"
	"time"

	"go.uber.org/zap"
)

func encryptBySha1(s string) string {
	o := sha1.New()
	o.Write([]byte(s))
	return hex.EncodeToString(o.Sum(nil))

}
func VerifyToken(tokenModel *models.TokenFormat) bool {
	flag := false
	token := setting.AppConf.JwtConfig.Secret
	sig := tokenModel.Signature
	timestamp := tokenModel.Timestamp
	nonce := tokenModel.Nonce
	slice := []string{token, timestamp, nonce}
	sort.Strings(slice)
	cryptStr := encryptBySha1(strings.Join(slice, ""))
	if sig == cryptStr {
		flag = true
	}
	return flag
}

func StoreWechatRemindCronService(remindInfo *models.RemindJobInfo) error {
	CronTimeNum, _ := strconv.Atoi(remindInfo.TimeNum)
	cronTime := int64(CronTimeNum) * timeUnit.GetTimeNumByMs(remindInfo.TimeUnitByMs)
	cronTask := remindInfo.RemindTask
	cronExecDurationTime := time.Duration(cronTime)

	cronModel := &models.RemindCronModel{
		TaskId: strconv.FormatInt(snowflake.GenId(), 10),
		//TaskId:   "123456",
		CronTime: cronExecDurationTime,
		Task:     cronTask,
		Reciever: remindInfo.RemindUser,
	}
	fmt.Println("------", cronModel)
	zap.L().Info("定时任务: ", zap.Any("msg", cronModel))
	err := models.StoreWechatRemindCron(cronModel)
	if err != nil {
		zap.L().Error("service StoreWechatRemindCronService err:", zap.Error(err))
		fmt.Println("service StoreWechatRemindCronService err : ", err)
		return err
	}
	return nil

}

func QueryCronTask(taskId string) (*models.RemindCronModel, error) {
	cronTask, err := models.GetCronTask(taskId)
	if err != nil {
		return nil, err
	}
	return cronTask, nil
}

func DeleteCronTask(taskId string) error {
	err := models.DeleteCronTask(taskId)
	if err != nil {
		return err
	}
	return nil
}
